package com.yl.androidutilscenter.weight;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ScreenUtils;

import java.util.Objects;

/**
 * @author
 * @version 1.0.0
 * @description: 左滑、右滑固定距离关闭页面
 * @date :2024/5/22
 */
public class SwipeBackLayout extends FrameLayout {
    private static final String TAG = SwipeBackLayout.class.getSimpleName();
    private int mTouchSlop;
    private int downX;
    private int downY;
    //滑动的距离阈值，未超过则恢复原始位置,默认是屏幕宽度一半
    private int scrollMinValue = ScreenUtils.getScreenWidth() / 2;
    //恢复到原始位置的动画持续时长
    private long animationDuration = 500L;
    private boolean isSilding;

    private ViewPager2 mChildView;

    //-1：从左往右滑   1：从右往左滑  0:未滑动
    private int tagLtrOrRtl = 0;
    private ScrollListener mScrollListener;

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }


    /**
     * 设置左右滑动结束时的事件监听
     *
     * @param mScrollListener
     */
    public void setScrollListener(ScrollListener mScrollListener) {
        this.mScrollListener = mScrollListener;
    }

    /**
     * 设置左右滑动的阈值
     */
    public void setScrollMinValue(int scrollMinValue) {
        this.scrollMinValue = scrollMinValue;
    }

    /**
     * 设置动画执行时长
     */
    public void setAnimationDuration(long animationDuration) {
        this.animationDuration = animationDuration;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        getCanScrollChildView(SwipeBackLayout.this);
    }

    /**
     * 事件拦截操作
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getRawX();
                // 满足此条件屏蔽SildingFinishLayout里面子类的touch事件
                if (Math.abs(moveX - downX) > mTouchSlop
                        && Math.abs((int) ev.getRawY() - downY) < mTouchSlop) {

                    if (mChildView != null) {
                        //显示的是第一个，如果继续从左往右滑动，则父控件拦截此事件
                        //或者显示的是最后一个，继续从右往左滑动，则父控件拦截此事件
                        if ((mChildView.getCurrentItem() == 0 && moveX > downX) ||
                                (mChildView.getCurrentItem() == Objects.requireNonNull(mChildView.getAdapter()).getItemCount() - 1 && moveX < downX)) {
                            return true;
                        } else {
                            //否则 子控件处理事件
                            return mChildView.onInterceptTouchEvent(ev);
                        }
                    } else {
                        return true;
                    }
                }


                break;
        }

        return super.onInterceptTouchEvent(ev);
    }

    /**
     * 查找子view，找到子view中最外层的viewpager2，处理与viewpager2的滑动冲突
     *
     * @param parent
     */
    private void getCanScrollChildView(ViewGroup parent) {
        if (mChildView != null) {
            return;
        }
        int childViewCount = parent.getChildCount();
        if (childViewCount > 0) {
            for (int i = 0; i < childViewCount; i++) {
                View view = parent.getChildAt(i);
                if (view instanceof ViewPager2) {
                    mChildView = (ViewPager2) view;
                    return;
                }
                if (view instanceof ViewGroup) {
                    getCanScrollChildView((ViewGroup) view);
                }
//                if (view instanceof ViewGroup) {
//                    int childViewCount2 = ((ViewGroup) view).getChildCount();
//                    for (int j = 0; j < childViewCount2; j++) {
//                        View view2 = ((ViewGroup) view).getChildAt(j);
//                        if (view2 instanceof ViewPager2) {
//                            mChildView = (ViewPager2) view2;
//                        }
//                    }
//                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //获取手指的坐标
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) event.getRawX();
                if (Math.abs(moveX - downX) > mTouchSlop
                        && Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
                    isSilding = true;
                }
                if (isSilding) {
                    setTranslationX(moveX - downX);
                }
                break;
            case MotionEvent.ACTION_UP:
                isSilding = false;
                //手指抬起时的x坐标
                float upX = event.getRawX();
                if (upX > downX) {//从左往右滑动
                    tagLtrOrRtl = -1;
                } else if (upX < downX) {//从右往左滑动
                    tagLtrOrRtl = 1;
                } else {
                    tagLtrOrRtl = 0;
                }
                if (Math.abs(upX - downX) >= scrollMinValue) {
                    //滑动距离满足阈值，关闭页面
                    scrollToClose();
                } else {
                    //此时滑动距离太小，未满足设置的阈值，view需要返回到原始位置
                    scrollToOriginal();
                }
                break;
        }

        return true;
    }

    //滑动到最外边并关闭activity
    private void scrollToClose() {
        float moveLength = getTranslationX();
        //
        int screenWidth =  ScreenUtils.getScreenWidth();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(moveLength, moveLength > 0 ? screenWidth : -screenWidth);
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (mScrollListener != null) {
                    if (tagLtrOrRtl == -1) {
                        mScrollListener.onLeft2RightFinishListener();
                    } else if (tagLtrOrRtl == 1) {
                        mScrollListener.onRight2LeftFinishListener();
                    }
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }
        });
        valueAnimator.addUpdateListener(animation -> {
            float value = (float) animation.getAnimatedValue();
            setTranslationX(value);
        });

        valueAnimator.setDuration(animationDuration);
        valueAnimator.start();
    }

    /**
     * 滑动距离未超过屏幕宽度的一半，返回原始位置,从右侧平移到左侧 或者从左侧平移到右侧
     * 使用动画，恢复到原始位置
     */
    private void scrollToOriginal() {
        float moveLength = getTranslationX();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(moveLength, 0.0f);
        valueAnimator.addUpdateListener(animation -> {
            float value = (float) animation.getAnimatedValue();
            setTranslationX(value);
        });

        valueAnimator.setDuration(animationDuration);
        valueAnimator.start();
    }


    public interface ScrollListener {
        /**
         * 从左往右滑动，滑动结束时的事件监听
         */
        void onLeft2RightFinishListener();

        /**
         * 从右往左滑动，滑动结束时的事件监听
         */
        void onRight2LeftFinishListener();
    }
}
